﻿using System.Windows;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using Microsoft.Phone.Shell;

namespace VisualStudioAchievements
{
    public partial class InputPage : PhoneApplicationPage
    {
        public InputPage()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            if (NavigationService.CanGoBack)
                NavigationService.GoBack();
        }

        private void btnAddUser_Click(object sender, System.EventArgs e)
        {
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            AddUser();
        }

        private void AddUser()
        {
            if (!Util.CheckIfUserExists(txtUsername.Text))
            {
                NinerReader reader = new NinerReader();
                reader.GetNiner(txtUsername.Text, true, niner =>
                {
                    BindingPoint.Instance.Niners.Add(niner);

                    Util.SerializeNiners();

                    if (NavigationService.CanGoBack)
                        NavigationService.GoBack();
                });
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                MessageBox.Show("User already on the list.");
            }
        }

        private void txtUsername_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                AddUser();
        }
    }
}